<?php
namespace app\models;

use Yii;
use yii\base\Model;
use app\models\StoreAdminModel;
use app\enum\EnumOther;
use app\models\BaseModel;


/**
 * Login form
 */
class StorePasswordForm extends Model
{
    public $adminname;
    public $email;
    public $oldpassword;
	public $newpassword;
	public $repassword;
	public $id;
    public $delete_flag;
	public $store_id;

	public function __construct($data)
	{
		$this->adminname   = isset($data['adminname']) ? $data['adminname'] :'';
		$this->email       = isset($data['email']) ? $data['email'] :'';
		$this->oldpassword = isset($data['oldpassword']) ? $data['oldpassword']:'';
		$this->newpassword = isset($data['newpassword'])? $data['newpassword']:'';
		$this->repassword  = isset($data['repassword']) ? $data['repassword'] : '';
		$this->id          = isset($data['id']) ? $data['id'] :'';
		$this->delete_flag = isset($data['delete_flag']) ? $data['delete_flag'] : 0;
		$this->store_id    = isset($data['store_id']) ? $data['store_id'] : 0;
	}
	
	/**
	 * @desc 更改个人信息
	 * @author liaojianwen
	 * @date 2016-11-15
	 */
	public function changeInfo()
	{
		$this->validate();
		$id = $this->id;
		$storeAdmin =  StoreAdminModel::findIdentity($id);
		$password = $storeAdmin->password_hash;
		if($this->adminname == $storeAdmin->username){
		} else{
			$storeAdmin->username = $this->adminname;//更改用户名
		}
		if($this->email == $storeAdmin->email){
		} else{
			$storeAdmin->email = $this->email;//emall
		}
		if($this->delete_flag == $storeAdmin->delete_flag){
		} else{
			$storeAdmin->delete_flag = $this->delete_flag;//是否删除
		}
		if($this->store_id == $storeAdmin->store_id){
		} else{
			$storeAdmin->store_id = $this->store_id;//门店id
		}
		if(!empty($this->oldpassword)){
			//有填写旧密码 即更改密码
			if (Yii::$app->getSecurity ()->validatePassword ( $this->oldpassword, $password )) {
				if ($this->newpassword == $this->repassword) {
					$newPass = Yii::$app->security->generatePasswordHash ( $this->newpassword );
					$storeAdmin->password_reset_token = '';
					$storeAdmin->password_hash = $newPass;
				} else {
					return handleApiFormat(EnumOther::ACK_FAILURE,'','newpassword do not eq to repassword');
				}
			} else {
				return handleApiFormat(EnumOther::ACK_FAILURE,'','oldpassword is not correct');
			}
		}

		if($storeAdmin->save()){
			return handleApiFormat(EnumOther::ACK_SUCCESS,true);
		}else{
			return handleApiFormat(EnumOther::ACK_FAILURE,'','save failure');
		}
	}

}
